Question:
How to fetch an array of IDs instead of array objects using a "with" statement?

In Laravel's Eloquent ORM, when you use the with method to eager load relationships, the result will include the related objects by default. If you want to fetch an array of IDs instead of array objects, you can use the pluck method to retrieve only the IDs from the relationship.


Here is the code:


public static function list()

{

    $objects = static::with(['links' => function($query) {

        $query->select('link_id');

    }])->get();


    // Iterate through the objects and pluck the link_ids

    $result = $objects->map(function ($object) {

        return [

            'id' => $object->id,

            'links' => $object->links->pluck('link_id')->toArray(),

        ];

    });


    return $result->toArray();

}


Credit:> Stackoverflow


Suggested blogs:

>How to Build a RESTful API Using Node Express and MongoDB- Part 1

>Integrate SASS into the build and consume a UI toolkit

>Use Firebase Realtime Database with ASP.NET MVC App

>Building Web API using ASP.NET (C#)

>CRUD Operations In ASP.NET Core Using Entity Framework Core Code First with Angularjs

>How to make a single result from a database using MySQL?

>Testing react components using Hooks and Mocks

>How to build an Electron application from scratch?


Ritu Singh

Ritu Singh

Submit
0 Answers